<template>
  <div class="users">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-input
        placeholder="请输入内容"
        v-model="pageinfo.query"
        class="input-with-select"
      >
        <el-button
          slot="append"
          icon="el-icon-search"
          @click="search"
        ></el-button>
      </el-input>
      <el-button type="primary" class="add" @click="addOK">添加用户</el-button>
      <el-table :data="tableData" border stripe style="width: 100%">
        <el-table-column
          fixed
          type="index"
          width="40"
          label="#"
        ></el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#409eff"
              inactive-color="#dcdfe6"
              @change="status(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <!-- <el-button @click="handleClick(scope.row)" type="text" size="small"
            >查看</el-button> -->
            <!-- <el-button type="text" >编辑</el-button> -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="edit(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="del(scope.row.id)"
            ></el-button>

            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="small"
                @click="Addroles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="pageinfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size.sync="pageinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户 -->
    <el-dialog
      :title="editId ? '修改用户' : '添加用户'"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="ruleForm.username"
            :disabled="editId ? true : false"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="editId ? false : true">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input
            v-model="ruleForm.mobile"
            oninput="value=value.replace(/[^\d]/g,'');if(value.length > 11)value = value.slice(0, 11)"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="dialogFormVisibles">
      <p>当前的用户：{{ roleslist.username }}</p>
      <p>当前的角色：{{ roleslist.role_name }}</p>
      <!-- <el-form :model="form">
        <el-form-item label="分配新角色">
          <el-select v-model="form.persona" placeholder="请选择">
            <el-option
              :label="item.roleName"
              :value="item.roleName"
              v-for="(item, index) in getList"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form> -->
      <p>
        分配新角色：<el-select v-model="value" placeholder="请选择">
          <el-option
            v-for="item in getList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </p>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibles = false">取 消</el-button>
        <el-button type="primary" @click="addroles">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  pleaUsers,
  pleaDelete,
  pleaState,
  pleaAdd,
  pleaEdit,
  pleaRoles,
  pleaPersona,
} from "../utils/http";
export default {
  data() {
    return {
      pageinfo: {
        query: "", //搜索
        pagenum: 1, //当前页
        pagesize: 5, //每页条数
      },
      total: 0, //总页数
      tableData: [], //接收数据
      dialogFormVisible: false, //添加
      dialogFormVisibles: false, //分配角色
      ruleForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 ~ 10 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6 ~ 15 个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { min: 11, message: "手机号格式不正确", trigger: "blur" },
        ],
      },
      editId: "", //保存修改id
      rolesId: "", //保存角色id
      roleslist: [], //回填角色
      getList: [], //获取新角色列表
      form: {
        persona: "",
      },
      value: "",
    };
  },
  created() {
    this.getusers();
  },
  methods: {
    getusers() {
      pleaUsers({
        query: this.pageinfo.query,
        pagenum: this.pageinfo.pagenum,
        pagesize: this.pageinfo.pagesize,
      }).then((res) => {
        // console.log(res);
        this.total = res.data.total;
        this.tableData = res.data.users;
      });
    },
    //添加
    addOK() {
      this.dialogFormVisible = true;
      this.ruleForm = {
        username: "",
        password: "",
        email: "",
        mobile: "",
      };
      this.editId = "";
    },
    //修改
    edit(row) {
      this.dialogFormVisible = true;
      this.editId = row.id;
      this.ruleForm = {...row};
    },
    //确定添加
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.editId) {
            //修改
            pleaEdit(
              this.ruleForm // email: this.ruleForm.email,
              // id: this.editId,
              // mobile: this.ruleForm.mobile,
            ).then((res) => {
              console.log(this.ruleForm);
              console.log(res);
              if (res.meta.status == 200) {
                this.getusers();
                this.dialogFormVisible = false;
                this.$message({
                  type: "success",
                  message: res.meta.msg,
                });
              } else {
                this.$message({
                  type: "danger",
                  message: res.meta.msg,
                });
              }
            });
          } else {
            //添加
            pleaAdd(this.ruleForm).then((res) => {
              console.log(res);
              if (res.meta.status == 201) {
                this.getusers();
                this.dialogFormVisible = false;
                this.$message({
                  type: "success",
                  message: res.meta.msg,
                });
              } else {
                this.$message({
                  type: "danger",
                  message: res.meta.msg,
                });
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogFormVisible=false
    },
    //搜索
    search() {
      this.getusers();
    },
    //每条页数
    handleSizeChange(val) {
      //   console.log(val);
      this.pageinfo.pagesize = val;
      this.getusers();
    },
    //当前页
    handleCurrentChange(val) {
      this.pageinfo.pagenum = val;
      this.getusers();
    },
    //删除
    del(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          pleaDelete({ id }).then((res) => {
            this.getusers();
          });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //修改状态
    status(row) {
      pleaState({ id: row.id, mg_state: row.mg_state }).then((res) => {
        // console.log(res);
        if (res.meta.status == 200) {
          this.getusers();
          this.$message({
            type: "success",
            message: res.meta.msg,
          });
        } else {
          this.$message({
            type: "danger",
            message: res.meta.msg,
          });
        }
      });
    },
    //分配角色
    Addroles(row) {
      this.rolesId = row.id;
      console.log(row);
      this.roleslist = row;
      // console.log(this.roleslist);
      this.dialogFormVisibles = true;
      pleaRoles().then((res) => {
        console.log(res);
        if (res.meta.status == 200) {
          this.getList = res.data.map((item, index) => {
            return { id: item.id, roleName: item.roleName };
          });
          console.log(this.getList);
        }
      });
    },
    //确定分配角色
    addroles() {
      pleaPersona({ id: this.rolesId, rid: this.value }).then((res) => {
        if (res.meta.status == 200) {
          this.getusers();
          this.dialogFormVisibles = false;
          this.$message({
            type: "success",
            message: res.meta.msg,
          });
        } else {
          this.$message({
            type: "danger",
            message: res.meta.msg,
          });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-pagination {
  margin-top: 15px;
}
::v-deep .input-with-select {
  width: 475px;
  margin-bottom: 20px;
}
.add {
  margin-left: 20px;
}
::v-deep .el-breadcrumb {
  margin-bottom: 20px;
}
::v-deep .el-form-item {
  margin-top: 20px;
  margin-bottom: 0;
}
</style>